async function downloadContent(type) {
    const url = document.getElementById('url').value;
    if (!url) {
        alert('请输入YouTube视频链接！');
        return;
    }

    // 显示加载动画
    document.getElementById('loading').classList.remove('hidden');
    document.getElementById('result').classList.add('hidden');

    try {
        const formData = new FormData();
        formData.append('url', url);
        formData.append('download_type', type);

        const response = await fetch('/download', {
            method: 'POST',
            body: formData
        });

        const data = await response.json();

        if (data.error) {
            alert('下载失败：' + data.error);
            return;
        }

        // 更新界面显示
        document.getElementById('thumbnail').src = data.thumbnail;
        document.getElementById('title').textContent = data.title;
        document.getElementById('uploader').textContent = '上传者：' + data.uploader;
        document.getElementById('duration').textContent = '时长：' + formatDuration(data.duration);
        document.getElementById('view_count').textContent = '观看次数：' + data.view_count;

        // 更新预览
        if (type === 'video') {
            document.getElementById('video-preview').classList.remove('hidden');
            document.getElementById('audio-preview').classList.add('hidden');
            document.querySelector('#video-preview video source').src = data.file_path;
            document.querySelector('#video-preview video').load();
        } else {
            document.getElementById('audio-preview').classList.remove('hidden');
            document.getElementById('video-preview').classList.add('hidden');
            document.querySelector('#audio-preview audio source').src = data.file_path;
            document.querySelector('#audio-preview audio').load();
        }

        document.getElementById('result').classList.remove('hidden');
    } catch (error) {
        alert('下载失败：' + error.message);
    } finally {
        document.getElementById('loading').classList.add('hidden');
    }
}

function formatDuration(seconds) {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const remainingSeconds = seconds % 60;

    let result = '';
    if (hours > 0) {
        result += `${hours}小时`;
    }
    if (minutes > 0) {
        result += `${minutes}分钟`;
    }
    if (remainingSeconds > 0 || result === '') {
        result += `${remainingSeconds}秒`;
    }
    return result;
} 